package cn.tramy.pinxian.task.application.command

import cn.tramy.pinxian.common.util.logger
import cn.tramy.pinxian.task.domain.model.Task
import cn.tramy.pinxian.task.domain.repository.TaskRepository
import cn.tramy.pinxian.wind.command.annotation.CommandHandler
import cn.tramy.pinxian.wind.command.annotation.CommandHandlerAware
import org.springframework.beans.factory.annotation.Autowired
import reactor.core.publisher.Mono
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*

@CommandHandlerAware
class TaskCommandHandler {

    companion object {
        private val LOGGER = logger(TaskCommandHandler::class.java)
    }

    @Autowired
    private lateinit var taskRepository: TaskRepository


    //    @Transactional
    @CommandHandler
    fun processCreation(command: CreateTask) {

        val timer: LocalDateTime? = command.timer?.let { LocalDateTime.parse(it, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) }

        val task = Task(UUID.randomUUID().toString(), command.content, timer, createAt = LocalDateTime.now())

        this.taskRepository.save(task)
    }

    @CommandHandler
    fun processFinish(finishTask: FinishTask) {
        Mono.fromCallable { this.taskRepository.getOne(finishTask.uid) }.doOnError {
            LOGGER.error("can not find Task[${finishTask.uid}]")
            throw it
        }.subscribe {
            it.finish();this.taskRepository.save(it)
        }
    }
}